import React, { createContext, useReducer, useState } from 'react';
import { Switch } from "antd";
import { S_MAN_LAYOUT } from "../utils/constant";
import store from "store";

// Context
export const LayoutContext = createContext({});

// Reducer
export const LayoutReducer = (state: object, action: {
  type: string;
  data: any;
}) => {
  switch(action.type) {
    case "SET_LAYOUT":
      store.set(S_MAN_LAYOUT, action.data.current);
      return {
        ...state,
        ...action.data
      }
  }
  return state;
}

export const LayoutProvider = (props: any) => {
  const [layout, dispatcher] = useReducer(LayoutReducer, {
    current: store.get(S_MAN_LAYOUT) || 'main'
  });

  function setLayout(value: string) {
    dispatcher({
      type: 'SET_LAYOUT',
      data: {
        current: value
      }
    });
  }

  const isMain = layout.current === "main";
  const toggle = () => setLayout(isMain ? "sky" : "main");
  const renderSwitch = () => {
    return (
      <Switch
        checkedChildren="Sky"
        unCheckedChildren="Main"
        defaultChecked={isMain}
        onClick={(() => { toggle()})}
      />
    )
  }

  return (
    <LayoutContext.Provider
      value={{
        dispatcher,
        ...layout,
        isMain,
        renderSwitch
      }}>
      {props.children}
    </LayoutContext.Provider>
  )
}